package com.zhixing.pay.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.zhixing.pay.domain.dto.TransactionQueryParams;
import com.zhixing.pay.domain.vo.TransactionRecordVO;
import com.zhixing.pay.mapper.TransactionRecordMapper;
import com.zhixing.pay.service.TransactionRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zhixing.common.constant.Constant.*;

@Service
@RequiredArgsConstructor
public class TransactionRecordServiceImpl implements TransactionRecordService {

    private final TransactionRecordMapper transactionRecordMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<TransactionRecordVO> getTransactionRecord(TransactionQueryParams transactionQueryParams) {
        // 查询缓存
        String redisKey = ZHIXING_TRANSACTION_RECORD + transactionQueryParams.getWalletId() + ":" + transactionQueryParams.getYearMonth();
        String hashKey = (transactionQueryParams.getTransactionType() == null ? "2" : transactionQueryParams.getTransactionType().getValue()) + ":" + transactionQueryParams.getPage();
        List<TransactionRecordVO> transactionRecordVOList = (List<TransactionRecordVO>) redisTemplate.opsForHash().get(redisKey, hashKey);
        if (CollUtil.isNotEmpty(transactionRecordVOList)) return transactionRecordVOList;

        // 查询数据库
        transactionRecordVOList = transactionRecordMapper.getTransactionRecord(transactionQueryParams);
        if (CollUtil.isNotEmpty(transactionRecordVOList)) {
            redisTemplate.opsForHash().put(redisKey, hashKey, transactionRecordVOList);
            redisTemplate.expire(redisKey, FIFTEEN_MINUTES, TimeUnit.MINUTES);
        }
        return transactionRecordVOList;
    }
}
